<template>
  <el-row>
    <div class="chat_top">
      <div class="chat_top_head clearBoth webchat-head">
        <div class="title">
          <div class="chat_title" v-show="webchatData.sName" :title="webchatData.sName + ' ' + chatMethod + ' ' + webchatData.createTime">
            <i :class="['im_' + webchatData.platform]"></i>
            <span class="customerName">{{(webchatData.currentCustomer && webchatData.currentCustomer.name) ? webchatData.currentCustomer.name : webchatData.leavemsg ? webchatData.sName + '(' + $t('webchat.leaveMessage') + ')' : webchatData.sName}}</span>
            <span class="custintent" v-show="webchatData.custIntention || webchatData.custIntention === 0">{{webchatData.custIntention + '%'}}</span>
            <span class="chat_title_time">{{webchatData.createTime}}</span>
          </div>
        </div>
      </div>
      <div class="chat_transfer" v-show="tabType === 'webchat_all' && webchatData.qc_grade && isQualityCheck" style="height:35px;line-height:35px;margin-right:10px;">
        <div class="fl">
          {{$t('qualityCheck.qualityGrade')}}：<span class="qc-grade-pink">{{webchatData.qc_grade}}</span>
        </div>
        <el-popover
          v-model="qualityCheckPopover"
          placement="top-start"
          :title="$t('call.qualityInspectionAppeals')"
          width="200"
          trigger="click"
          popper-class="call-qc-popover">
          <div class="qc-content">
            <p>{{$t('qualityCheck.qualityGrade')}}：{{$t('call.autoQcGrade', {autoQcGrade: webchatData.qc_grade})}}</p>
            <p style="line-height:2;word-wrap: break-word;">{{$t('qualityCheck.commentCont')}}：{{webchatData.qc_comment || ''}}</p>
            <textarea rows="3" style="width:100%;resize: vertical;" :placeholder="$t('call.placeholderCpmplain')" v-model.trim="comment"></textarea>
            <div style="text-align: right; margin: 20px 0 0 0">
              <el-button size="mini" type="text" @click="qualityCheckPopover = false">{{$t('public.cancel')}}</el-button>
              <el-button type="primary" size="mini" @click="commitQcComplain">{{$t('public.confirm')}}</el-button>
            </div>
          </div>
          <span slot="reference" class="iconfont icon-zhijianshensu" v-show="webchatData.user === $store.state.session.user._id" style="line-height:35px;"></span>
        </el-popover>
      </div>
      <div class="chat_transfer" v-show="webchatData.showFunBtn && tabType === 'webchat_todo'">
        <el-popover ref="popover2" v-show="tabType === 'webchat_todo'" placement="bottom" width="220" trigger="click" v-model.trim="popover2Show">
          <div class="popover2">
            <!--<el-input size="mini" class="inline-input" :placeholder="$t('public.pleaseEnter')"></el-input>-->
            <input type="text" :placeholder="$t('public.pleaseEnter')" class="popover2_input" v-model.trim="popover2Search" v-on:keyup="searchTree2"/>
            <div class="prompt" v-show="popoLoading">{{$t('webchat.loading')}}</div>
            <ul class="tree" v-show="chatHead.onlineAgentsTransfer.length">
              <li class="transfer_li_box" v-for="(model, index) in chatHead.onlineAgentsTransfer" :key="index">
                <ul v-show="model.AssignMembers.length" class="transfer_li_ul">
                  <li class="quickReSys transfer_li clearfix ellipsis" v-for="modelNew in model.AssignMembers" :key="modelNew._id">
                    <span class="cata-name ellipsis" @click.stop="inviteAgent(modelNew._id, modelNew.displayName)">{{modelNew.displayName}}</span>
                    <span class="chatNum ellipsis" @click.stop="inviteAgent(modelNew._id, modelNew.displayName)">（{{modelNew.chatNum}}{{$t('workbench.businessWait')}}）</span>
                  </li>
                </ul>
              </li>
            </ul>
            <div class="prompt" v-show="!chatHead.onlineAgentsTransfer.length && popoLoading === false">{{$t('webchat.noData')}}</div>
          </div>
        </el-popover>
        <div class="popover_btn_box" v-show="!webchatData.leavemsg">
          <el-tooltip class="item" effect="dark" :content="$t('webchat.laterProcess')" placement="bottom">
            <el-button type="text" v-show="!webchatData.laterProcess && flag !=='ecommerce'" class="iconfont icon-shaohouchuli1" size="mini" @click="handleLaterProcess"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" :content="$t('webchat.cancelLaterProcess')" placement="bottom">
            <el-button type="text" v-show="webchatData.laterProcess && flag !=='ecommerce'" class="iconfont icon-shaohouchuli" size="mini" @click="handleCancelLaterProcess"></el-button>
          </el-tooltip>
        </div>
        <el-popover ref="popover1" v-model="popover1Show" placement="bottom" width="220" trigger="manual">
          <webchatTransfer
            ref="transferRef"
            :transferVisible="popover1Show"
            :AssignTreeData="AssignTreeData"
            :popoLoading="popoLoading"
            :webchatData="webchatData"
            :onlineAgentsInvite="chatHead.onlineAgentsInvite"
            @searchTree="searchTree1"
            @transfer="transferSend">
          </webchatTransfer>
          <el-tooltip class="item" effect="dark" :content="isTransferIng ? $t('cti.cancleTransferBtn') : $t('webchat.sessionTransfer')" placement="bottom" slot="reference" v-show="isShowTranferSession && !webchatData.oldLeaveMsg">
            <el-button type="text" :class="[isTransferIng && 'close-icon', 'iconfont icon-zhuanjie1']" size="mini" @click="changePopover1"></el-button>
          </el-tooltip>
        </el-popover>
        <div class="popover_btn_box" v-show="!webchatData.leavemsg">
          <el-tooltip class="item" effect="dark" :content="$t('webchat.inviteSeats')" placement="bottom">
            <el-button type="text" v-show="webchatData.shwoInviteBtn" class="iconfont icon-yaoqing" v-popover:popover2 size="mini" @click="changePopover2"></el-button>
          </el-tooltip>
          <el-tooltip v-show="!webchatData.shwoInviteBtn" class="item" :content="$t('webchat.kickOutCollaborators')" placement="top">
            <el-button type="text" class="iconfont icon-tichuxiezuozuoxi" size="mini" @click.stop="changeShwoInviteBtn"></el-button>
          </el-tooltip>
        </div>
        <!--<el-button type="text" class="iconfont icon-tichuxiezuozuoxi" v-show="!webchatData.shwoInviteBtn" size="mini" @click.stop="changeShwoInviteBtn"></el-button>-->
        <el-tooltip class="item" effect="dark" :content="$t('webchat.endSession')" placement="bottom">
          <el-button type="text" class="iconfont icon-tuichu" @click.stop="getFinishReason" size="mini"></el-button>
        </el-tooltip>
      </div>
      <div v-if="!webchatData.showFunBtn && tabType === 'webchat_todo'" style="marginRight:10px">
        <el-tooltip class="item" effect="dark" :content="$t('webchat.exitSession')" placement="bottom">
          <el-button type="text" class="iconfont icon-tuichu" @click.stop="exitThreeSession" size="mini"></el-button>
        </el-tooltip>
      </div>
      <div class="chat_transfer" v-show="(tabType === 'webchat_all' || tabType === 'webchat_robot') && showGrabIcon">
        <el-tooltip class="item" :content="$t('webchat.pickUpChat')" placement="right">
          <el-button type="text" class="iconfont icon-qiangjie" size="mini" @click.stop="grabConversation"></el-button>
        </el-tooltip>
      </div>
      <div class="chat_transfer" v-show="(tabType === 'webchat_laterProcess')">
        <el-tooltip class="item" effect="dark" :content="$t('webchat.cancelLaterProcess')" placement="bottom">
          <el-button type="text" class="iconfont icon-shaohouchuli" size="mini" @click="handleCancelLaterProcess"></el-button>
        </el-tooltip>
      </div>
      <!-- 主动提交质检按钮 -->
      <submit-qc v-if="tabType === 'webchat_all' && isShowSubmitQc" :webchatData="webchatData"></submit-qc>
    </div>
    <end-session-box v-if="chatHead.dialogTableVisible" :info="chatHead" :deleteFlag="true" @endSession="endSessionFun"></end-session-box>
  </el-row>
</template>
<script type="text/javascript">
  import { deepClone, getStrLength, isHasFunc, updateOptions } from '@/utils/m7Utils'
  import EndSessionBox from './WebchatEndSession'
  import * as types from '@/store/modules/webchat/mutation-types.js'
  import * as typeMuta from '@/store/mutation-types.js'
  import bus from '@/store/eventBus'
  import webchatTransfer from '@components/business-modules/webchat/webchatTransfer'
  import SubmitQc from './submitQc.vue'
  import { pick } from 'lodash'
  function changeShowInvite (store, data) {
    return store.dispatch('changeInvite', data)
  }
  export default {
    name: 'WebchatConChatHead',
    props: {
      showGrabIcon: Boolean,
      VideoTipsDialog: Boolean,
      VideoActionTips: String
    },
    data () {
      return {
        flag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf',
        isQualityCheck: false,
        isShowTranferSession: true,
        comment: '', // 申訴內容
        qualityCheckPopover: false, // 查看原因&&申訴
        chatHead: {
          onlineAgentsInvite: [],
          onlineAgentsTransfer: [],
          defaultProps: {
            AssignMembers: 'AssignMembers',
            DisplayName: 'DisplayName'
          },
          remark: '',
          dialogTableVisible: false,
          endOptionsUl: [],
          EndSessionOptions: []
        },
        popover2Search: '',
        popoLoading: false,
        openPop2: {
          index: -1,
          isOn: false
        },
        popover2Show: false,
        AssignTreeData: [],
        pop2Clone: {},
        popover1Show: false,
        isEndTransferFlag: false,
        isShowSubmitQc: false, // 主动提交质检按钮
      }
    },
    watch: {
      $route (to) {
        if (to.path.indexOf('webchat_todo') > -1) {
          this.popover2Show = false
          this.popover1Show = false
        }
      }
    },
    computed: {
      isTransferIng() {  // 当前会话是否正在进行会话转接
        return this.webchatData.redirectToUser
      },
      chatMethod () {
        let platform = ''
        if (this.webchatData) {
          if (this.webchatData.platform === 'pc') {
            platform = this.$t('webchat.platformPc')
          } else if (this.webchatData.platform === 'wap') {
            platform = this.$t('webchat.platformWap')
          } else if (this.webchatData.platform === 'sdk') {
            platform = this.$t('webchat.platformApp')
          } else if (this.webchatData.platform === 'weixin') {
            platform = this.$t('webchat.platformWeixin')
          } else if (this.webchatData.platform === 'wxmini') {
            platform = this.$t('webchat.platformWeixinMini')
          } else if (this.webchatData.platform === 'weibo') {
            platform = this.$t('webchat.platformWeibo')
          } else if (this.webchatData.platform === 'dy') {
            platform = this.$t('webchat.TikTok')
          } else if (this.webchatData.platform === 'wxkf') {
            platform = this.$t('webchat.platformWXKF')
          } else {
            platform = this.$t('webchat.platformOther')
          }
        }
        return platform
      },
      webchatData () {
        //  会话的详细信息
        if (this.tabType === 'webchat_todo' && this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId]) {
          this.chatHead.remark = this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId].remark
          return this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId]
        } else if (this.tabType === 'webchat_all' && this.$store.state.webchat.current.webchat_all.currentSession) {
          let data = deepClone(this.$store.state.webchat.current.webchat_all.currentSession) || {}
          if (data.qc_grade === 0) {
            data.qc_grade = data.qc_grade.toString()
          }
          if (!data.QC_SUBMIT) {
            data.QC_SUBMIT = false
          }
          this.comment = ''
          return data
        } else if (this.tabType === 'webchat_robot' && this.$store.state.webchat.current.webchat_robot.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_robot.currentSession)
        } else if (this.tabType === 'webchat_laterProcess' && this.$store.state.webchat.current.webchat_laterProcess.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_laterProcess.currentSession)
        } else if (this.tabType === 'webchat_queue' && this.$store.state.webchat.current.webchat_queue.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_queue.currentSession)
        } else {
          return {}
        }
      },
      tabType () {
        let arr = this.$route.path.split('/')
        return arr[3]
      },
      sessionId () {
        let arr = this.$route.path.split('/')
        return arr[4] || ''
      },
      isVideoing () {
        return this.$store.state.webchat.isVideoing
      },
      isInviteVideo () {
        return this.$store.state.webchat.isinviteVideo
      },
      videoSessionid () {
        return this.$store.state.webchat.videoChatData.videoSessionid
      },
      isScreenShareing () {
        return this.$store.state.webchat.isShareScreening
      },
      screenShareSessionId () {
        return this.$store.state.webchat.shareScreenSessionid
      },
      closeSessionList () {
        return this.$store.state.webchat.current[this.tabType].currentSession[this.sessionId].closeSessionList || []
      }
    },
    methods: {
      async cancelTransfer () {
        const param = pick(this.webchatData, ['_id', 'redirectToUser'])
        await this.$store.dispatch('redirectSessionCancel', param)
        this.updateChatData('redirectToUser', null)
        this.$message.success(this.$t('cti.cancelTransferSuccess'))
      },
      updateChatData (key, val) {
        this.$set(this.webchatData, key, val)
      },
      // 设置为稍后处理
      handleLaterProcess () {
        let ids = []
        ids.push(this.sessionId)
        this.$store.dispatch('markLaterProcess', {ids: ids}).then(res => {
          if (res.success) {
            this.$message.success(this.$t('webchat.laterProcessSuccess'))
            // 更新列表中的稍后处理状态
            this.$store.commit(types.UPDATE_LATERPROCESS_STATUS, {_id: this.sessionId, status: true})
          }
        })
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-在线咨询标记稍后处理'])
      },
      // 取消当前会话稍后处理状态
      handleCancelLaterProcess () {
        let ids = []
        ids.push(this.sessionId)
        this.$store.dispatch('removeLaterProcess', {ids: ids}).then(res => {
          if (res.success) {
            // 更新列表中的稍后处理状态
            this.$store.commit(types.UPDATE_LATERPROCESS_STATUS, {_id: this.sessionId, status: false})
            if (this.tabType === 'webchat_laterProcess') {
              // 刷新左侧列表
              bus.$emit('laterProcessRefresh', '')
              // 重置右侧组件
              this.$store.commit('BLANK', 'webchat_laterProcess')
              this.$router.replace({path: '/index/webchat/webchat_laterProcess'})
            }
          }
        })
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-在线咨询取消单个稍后处理'])
      },
      commitQcComplain () {
        if (this.comment.length <= 0) {
          this.$message.error(this.$t('call.placeholderCpmplain'))
          return
        }
        if (getStrLength(this.comment) > 400) { // 备注内容最多200个字
          this.$message.error(this.$t('call.limitChineseCharacters'))
          return
        }
        this.qualityCheckPopover = false
        let data = {'_id': this.sessionId, 'comment': this.comment}
        this.$store.dispatch('submitAppealCall', data).then(resp => {
          if (resp && resp.success) {
            this.$message.success(this.$t('call.copmplainSuccess'))
          }
        })
      },
      endSessionFun (flag, option, remark) {
        if (flag) {
          if (!option || option === '') {
            this.$message.error(this.$t('public.chooseEndSession'))
            return
          } else {
            let actName = option.split('__')[1]
            let finishKey = option.split('__')[0]
            let data = {
              _id: this.webchatData._id,
              sid: this.webchatData.sid,
              finishReason: actName,
              finishKey: finishKey,
              remark: remark || ''
            }
            this.$store.dispatch('finishWebchatSession', data).then(() => {
              this.$store.commit('BLANK', 'webchat_todo')
              this.$router.replace({path: '/index/webchat/webchat_todo'})
            })
            this.chatHead.dialogTableVisible = false
          }
        } else {
          this.chatHead.dialogTableVisible = false
        }
      },
      searchTree1 (serchName, data) {
        if (serchName) {
          this.chatHead.onlineAgentsInvite = data
        } else {
          this.chatHead.onlineAgentsInvite = deepClone(this.AssignTreeData)
        }
      },
      searchTree2 () {
        let that = this
        let str = that.popover2Search
        let schStr = that.trim(str)
        let data = []
        if (schStr) {
          that.pop2Clone.forEach((item) => {
            let obj = deepClone(item)
            let dataLi = {
              AssignMembers: []
            }
            if (obj.AssignMembers && obj.AssignMembers.length) {
              for (let i = 0; i < obj.AssignMembers.length; i++) {
                let liName = obj.AssignMembers[i].displayName
                if (liName.indexOf(schStr) !== -1) {
                  dataLi.AssignMembers.push(obj.AssignMembers[i])
                }
              }
              data.push(dataLi)
            }
          })
          that.chatHead.onlineAgentsTransfer = data
        } else {
          that.chatHead.onlineAgentsTransfer = deepClone(that.pop2Clone)
        }
      },
      changePopover1 () {
        if (this.isTransferIng) {
          return this.cancelTransfer()
        }
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'FE-转接会话'])
        if (this.isVideoing && this.webchatData._id === this.videoSessionid) {
          this.$emit('VideoTips', this.$t('videoChat.operaAfterVideo'))
          return
        }
        if (this.isInviteVideo && this.webchatData._id === this.videoInviteSessionId) {
          this.$emit('VideoTips', this.$t('videoChat.operaAfterVideo'))
          return
        }
        if (this.isScreenShareing && this.webchatData._id === this.screenShareSessionId) {
          this.$emit('VideoTips', this.$t('screenShare.operaAfterShare'))
          return
        }
        this.popover1Show = true
        this.popoLoading = true
        this.chatHead.onlineAgentsInvite = []
        this.$store.dispatch('getOnlineAgent', {data: {toPeer: this.webchatData.toPeer}}).then((res) => {
          if (res.length) {
            this.chatHead.onlineAgentsInvite = res
          }
          this.AssignTreeData = deepClone(res)
          this.popoLoading = false
        })
      },
      changePopover2 () {
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'FE-三方邀请会话'])
        if (this.isVideoing && this.webchatData._id === this.videoSessionid) {
          this.$emit('VideoTips', this.$t('videoChat.operaAfterVideo'))
          return
        }
        if (this.isInviteVideo && this.webchatData._id === this.videoInviteSessionId) {
          this.$emit('VideoTips', this.$t('videoChat.operaAfterVideo'))
          return
        }
        if (this.isScreenShareing && this.webchatData._id === this.screenShareSessionId) {
          this.$emit('VideoTips', this.$t('screenShare.operaAfterShare'))
          return
        }
        this.popoLoading = true
        this.popover2Search = ''
        this.chatHead.onlineAgentsTransfer = []
        this.$store.dispatch('getPeerOnlineAgent', this.webchatData.toPeer).then((res) => {
          if (res.length) {
            this.chatHead.onlineAgentsTransfer = res
          }
          this.openPop2.index = -1
          this.openPop2.isOn = false
          this.pop2Clone = deepClone(res)
          this.popoLoading = false
        })
      },
      togglePop2: function (index) {
        if (index === this.openPop2.index) {
          this.openPop2.isOn = !this.openPop2.isOn
        } else {
          this.openPop2.index = index
          this.openPop2.isOn = true
        }
      },
      transferSend ({model, type, modelagent, transfer}) {
        if (this.isVideoing && this.webchatData._id === this.videoSessionid) {
          this.$emit('VideoTips', this.$t('videoChat.operaAfterVideo'))
          return
        }
        if (this.isInviteVideo && this.webchatData._id === this.videoInviteSessionId) {
          this.$emit('VideoTips', this.$t('videoChat.operaAfterVideo'))
          return
        }
        if (this.isScreenShareing && this.webchatData._id === this.screenShareSessionId) {
          this.$emit('VideoTips', this.$t('screenShare.operaAfterShare'))
          return
        }
       
        let sendData = {
          _id: this.webchatData._id,
          sid: this.webchatData.sid
        }
        if (type === 'transferGroup') { // 转接技能组
          sendData.queueId = model._id
          sendData.toPeer = model.Exten
        } else { // 转接单个坐席
          sendData.toPeer = model.Exten
          sendData.toUserName = modelagent.displayName
          sendData.toUser = modelagent._id
          sendData.toPeerBefore = this.webchatData.toPeer
          sendData.custId = this.webchatData.custId
          sendData.sName = (this.webchatData.currentCustomer && this.webchatData.currentCustomer.name) ? this.webchatData.currentCustomer.name : this.webchatData.sName
          sendData.cust_status = this.webchatData.cust_status
        }
        // console.log('***transfer***', transfer)
        Object.assign(sendData, transfer || {})
        const hasConfirm = transfer.redirectWebchatSessionConfirmFlag
        if (hasConfirm) {
          Object.assign(sendData, {noClose: true})
          const { redirectConfirmQueueAgent, toUser } = sendData
          const redirectToUser = redirectConfirmQueueAgent || toUser
          this.updateChatData('redirectToUser', redirectToUser)
        }
        
        this.$store.dispatch('redirectWebchatSession', sendData).then((res) => {
          if (sendData.redirectWebchatSessionComment) {
            this.$store.commit('webchat/UPDATE_WEBCHAT_TODO', {
              channelId: this.webchatData._id,
              key: 'remark',
              val: sendData.redirectWebchatSessionComment
            })
          }
          this.popover1Show = false
          if (hasConfirm) {
            return
          }
          this.isEndTransferFlag = false
          if (res) {
            this.popover1Show = false
            this.$store.commit('BLANK', 'webchat_todo')
            this.$router.replace({path: '/index/webchat/webchat_todo'})
          }
        })
      },
      changeShwoInviteBtn () {
        let self = this
        this.$confirm(this.$t('webchat.sureKickOutCollaborators'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          self.changeInviteBtn(self)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('webchat.cancelKickOutCollaborators')
          })
        })
      },
      changeInviteBtn (self) {
        if (this.webchatData.shwoInviteBtn) {
          this.$message({type: 'info', message: this.$t('webchat.collaboratorsIsKickOut')})
          return
        }
        changeShowInvite(self.$store, false)
        this.$store.dispatch('kickGroupSession', {_id: self.webchatData._id, sid: self.webchatData.sid}).then(res =>{})
      },
      getFinishReason () {
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-对话框结束会话'])
        if (this.isVideoing && this.webchatData._id === this.videoSessionid) {
          this.$emit('VideoTips', this.$t('videoChat.operaAfterVideo'))
          return
        }
        if (this.isInviteVideo && this.webchatData._id === this.videoInviteSessionId) {
          this.$emit('VideoTips', this.$t('videoChat.operaAfterVideo'))
          return
        }
        if (this.isScreenShareing && this.webchatData._id === this.screenShareSessionId) {
          this.$emit('VideoTips', this.$t('screenShare.operaAfterShare'))
          return
        }
        if (this.closeSessionList) {
          if (this.closeSessionList.status !== 'close') {
            this.chatHead.dialogTableVisible = true
          } else {
            let data = {
              _id: this.webchatData._id,
              sid: this.webchatData.sid,
              finishReason: this.closeSessionList.finishReason,
              finishKey: this.closeSessionList.finishKey,
              remark: this.webchatData.remark || ''
            }
            this.$store.dispatch('finishWebchatSession', data).then(() => {
              this.$store.commit('BLANK', 'webchat_todo')
              this.$router.replace({path: '/index/webchat/webchat_todo'})
            })
          }
        }
      },
      trim (data) {
        let _str = data
        return _str.replace(/(^\s*)|(\s*$)/g, '')
      },
      grabConversation () {
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'FE-抢接会话'])
        let data = {
          _id: this.webchatData._id,
          toUser: this.$store.state.session.user._id,
          toUserName: this.$store.state.session.user.displayName,
          sid: this.webchatData.sid,
          'currUser': this.webchatData.user
        }
        this.$store.dispatch('grabWebchatSession', data).then(() => {
          // 注释： 抢接后手动将当前信息填入webchat_todo 的 chatInfo 里，避免后续处理报错，因为后端推过来的抢接会话信息有时间差
          let chatInfo = this.webchatData
          this.$store.commit(types.INSERT_GRABSESSION, chatInfo)
          // 注释end
          this.$router.push('/index/webchat/webchat_todo/' + this.webchatData._id + '/webchat')
          let isLeaveMsg = this.webchatData.leavemsg ? true : false
          let type = 'grabWebchatSession'
          bus.$emit('initiatingWebchatFun', isLeaveMsg, type)
        })
      },
      inviteAgent (invitedUser, invitedUserName) {
        if (this.isVideoing && this.webchatData._id === this.videoSessionid) {
          this.$emit('VideoTips', this.$t('videoChat.operaAfterVideo'))
          return
        }
        if (this.isInviteVideo && this.webchatData._id === this.videoInviteSessionId) {
          this.$emit('VideoTips', this.$t('videoChat.operaAfterVideo'))
          return
        }
        if (this.isScreenShareing && this.webchatData._id === this.screenShareSessionId) {
          this.$emit('VideoTips', this.$t('screenShare.operaAfterShare'))
          return
        }
        let inviteAgent = {
          _id: this.webchatData._id,
          sid: this.webchatData.sid,
          invitedUser: invitedUser,
          invitedUserName: invitedUserName
        }
        this.$store.dispatch('inviteGroupSession', inviteAgent).then((res) => {
          if (res) {
            //  展示邀请座席页面
            let data = deepClone(this.inviteCon)
            if (data) {
              this.popover2Show = false
              return
            }
            data = !data
            changeShowInvite(this.$store, data)
            //  切换邀请座席按钮和踢出邀请座席按钮
            //  popover2隐藏
            this.popover2Show = false
          }
        })
      },
      batchTransferPopFun (e) {
        if (this.$refs.popover1 && !this.$refs.popover1.$el.contains(e.target)) {
          this.popover1Show = false
        }
      },
      exitThreeSession () {
        const sendData = {
          _id: this.webchatData._id,
          sid: this.webchatData.sid
        }
        this.$store.dispatch('quitGroupSession', sendData).then((res) => {
          if (res) {
            this.$store.commit('BLANK', 'webchat_todo')
            this.$router.replace({path: '/index/webchat/webchat_todo'})
            this.$message.success(this.$t('webchat.exitSessionSuccess'))
          }
        })
      }
    },
    components: {
      EndSessionBox,
      webchatTransfer,
      SubmitQc
    },
    mounted () {
      bus.$on('serHeaderImg', (data)=> {
          this.$store.commit(typeMuta.SER_HEADER_IMG, {data, sessionId: this.sessionId})
      })
    },
    beforeDestroy () {
      bus.$off('serHeaderImg')
    },
    beforeMount () {
      if (isHasFunc('func_autoqc_result_look', this.$store.state.session.user)) {
        this.isQualityCheck = true // 是否能查看质检评分结果
      }
      if (isHasFunc('func_not_tranfer_webchatSession', this.$store.state.session.user)) {
        this.isShowTranferSession = false
      }
      // 是否能主动提交质检
      if (isHasFunc('func_submitqc_webchatSession', this.$store.state.session.user)) {
        this.isShowSubmitQc = true
      }
      this.$store.dispatch('getCache', {type: 'channelDic'}).then((res) => {
        let _dics = ''
        for (let i = 0; i < res.length; i++) {
          if (res[i].type === 'webchat') {
            _dics = res[i].options || []
            break
          }
        }
        if (_dics.length === 0) {
          this.$message.error(this.$t('webchat.isNullByFinishKey'))
          return
        }
        updateOptions(_dics, {Arr: this.chatHead.EndSessionOptions})
        this.chatHead.endOptionsUl = this.chatHead.EndSessionOptions
        document.addEventListener('click', this.batchTransferPopFun)
      })
    },
    beforeDestroy () {
      document.removeEventListener('click', this.batchTransferPopFun)
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  @import "./style/webchatCon.styl"
  .close-icon
    position relative
    &::after
      content 'x'
      position absolute
      bottom 1px
      right 1px
      font-size 12px
  .webchat-head
    .custintent
      background: #00ade6;
      padding: 1px 6px;
      border-radius: 5px;
      color: #fff;
      margin-left 10px
      height 24px
      line-height 24px
  .im_pc:before
    content "\e713"
  .im_weixin:before
    content "\e715"
  .im_wxmini:before
    content "\e716"
  .im_wap:before
    content "\e714"
  .im_sdk:before
    content "\e671"
  .im_weibo:before
    content "\e6d1"
  .im_wxEnterprise:before
    content "\e747"
  .im_ocpc:before
    content "\e761"
  .im_dy:before
    content "\e8db"
  .im_wxkf:before
    content "\e754"
  .qc-grade-pink
    color $c-pink
  .icon-zhijianshensu
    color $c-main
  .icon-shaohouchuli
    color $c-main !important
  [class^='im_']
    font-family "iconfont" !important
    font-style normal
    -webkit-font-smoothing antialiased
    color $cf-level4
    margin-right 4px
    margin-left 14px
  .transfer_group
    overflow: hidden
    text-overflow: ellipsis
    white-space: nowrap
    padding-right: 10px
  .transfer_li_ul
    .transfer_li
      .cata-name
        display inline-block
        width calc(100% - 70px)
      .chatNum
        display: inline-block;
        width: 70px;
</style>
